package cn.takovh.zpl;

import javafx.stage.FileChooser;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {
    public static final String DESKTOP = System.getProperty("user.home") + File.separator + "Desktop";
    public static final String MUSIC = System.getProperty("user.home") + File.separator + "Music";
    public static final String[] ZPL_EXT = new String[]{"*.zpl"};
    public static final String[] MUSIC_EXT = new String[]{"*.mp3", "*.m4a", "*.flac"};

    //过滤选择文件类型
    public static FileChooser.ExtensionFilter zplExtensionFilter = new FileChooser.ExtensionFilter("播放列表", ZPL_EXT);
    public static FileChooser.ExtensionFilter musicExtensionFilter = new FileChooser.ExtensionFilter("歌曲", MUSIC_EXT);
    public static File initialDirectory = new File(MUSIC);

    public static Document parse(File file) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(file);
        return document;
    }

    public static void writeFile(Document document, File file) throws IOException {
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        OutputFormat format = OutputFormat.createPrettyPrint();
        // 去除自带的xml文档说明
        format.setSuppressDeclaration(true);
        XMLWriter writer = new XMLWriter(fileOutputStream, format);
        writer.write(document);
        writer.flush();
        writer.close();
    }

    public static void writeConsole(Document document) throws IOException {
        OutputFormat format = OutputFormat.createPrettyPrint();
        // 去除自带的xml文档说明
        format.setSuppressDeclaration(true);
        XMLWriter writer = new XMLWriter(System.out, format);
        writer.write(document);
        writer.flush();
    }

    public static List<File> listMusicFiles(File dir) {
        if (dir == null) {
            return new ArrayList<>();
        }
        File[] files = dir.listFiles(f -> {
            if (f.isDirectory()) {
                return false;
            }
            String fileName = f.getName().toLowerCase();
            return fileName.endsWith(".mp3") || fileName.endsWith(".m4a") || fileName.endsWith(".flac");
        });
        if (files == null) {
            return new ArrayList<>();
        }
        return Arrays.asList(files);
    }

    public static boolean stringNotEmpty(String str) {
        return str != null && !str.equals("");
    }

    public static boolean stringIsEmpty(String str) {
        return str == null || str.equals("");
    }
}
